<script setup lang="ts">
// 引入vue Api
import { ref } from 'vue'

// 引入自定义组件
import HomeNavBar from './components/HomeNavBar.vue' // 引入homeNavBar组件
import ClassifyNav from './components/ClassifyNav.vue' // 引入classifyNav组件
import HotPanel from './components/HotPanel.vue' // 引入hotPanel组件
import PageSkeleton from './components/PageSkeleton.vue'

// 引入生命周期函数
import { onLoad } from '@dcloudio/uni-app'

// 引入接口
import { getHomeBanner, getHomeClassify, getHomeHotPanel } from '@/services/homeApi' // 引入homeApi

// 引入类型
import type { BannerItem, ClassifyNavItem, HotPanelItem } from '@/types/home'
import type { XtxGuessInstance } from '@/types/component'

// 轮播图 ------------------------------------------
// 轮播图数据
const bannerList = ref<BannerItem[]>([])
// 获取轮播图数据
const getBannerList = async () => {
  const res = await getHomeBanner()
  bannerList.value = res.result
}
// 分类 ------------------------------------------
// 分类数据
const classifyList = ref<ClassifyNavItem[]>([])
// 获取分类数据
const getClassifyList = async () => {
  const res = await getHomeClassify()
  classifyList.value = res.result
}

// 热门面板 -------------------------------------------
const hotPanelList = ref<HotPanelItem[]>([])
// 获取热门面板数据
const getHotPanelList = async () => {
  const res = await getHomeHotPanel()
  hotPanelList.value = res.result
}

// 调用获取所有面板数据 -------------------------------------------
const isShow = ref(false) // 是否显示骨架屏
onLoad(async () => {
  isShow.value = true // 显示骨架屏
  await Promise.all([getBannerList(), getClassifyList(), getHotPanelList()])
  isShow.value = false // 隐藏骨架屏
})

// 下拉加载 -------------------------------------------
const guessVC = ref<XtxGuessInstance>()
const onTolower = () => {
  guessVC.value?.getMore()
}

// 上拉刷新 ----------------------------------------------
const isTriggered = ref<boolean>(false)
const onRefresherrefresh = async () => {
  // 开启上拉动画
  isTriggered.value = true
  // 重置数据
  guessVC.value?.resetData()
  await Promise.all([
    getBannerList(),
    getClassifyList(),
    getHotPanelList(),
    guessVC.value?.getMore(),
  ])
  // 关闭上拉动画
  isTriggered.value = false
}
</script>

<template>
  <!-- 导航栏 -->
  <HomeNavBar></HomeNavBar>
  <!-- 骨架屏 -->
  <PageSkeleton v-if="isShow" />
  <!-- 滚动视图 -->
  <template v-else>
    <scroll-view
      refresher-enabled
      @refresherrefresh="onRefresherrefresh"
      :refresher-triggered="isTriggered"
      class="scroll-view"
      scroll-y
      @scrolltolower="onTolower"
    >
      <!-- 轮播图 -->
      <XtxSwiper :list="bannerList"></XtxSwiper>
      <!-- 分类导航 -->
      <ClassifyNav :list="classifyList"></ClassifyNav>
      <!-- 热门面板 -->
      <HotPanel :list="hotPanelList"></HotPanel>
      <!-- 猜你喜欢 -->
      <XtxGuess ref="guessVC"></XtxGuess>
    </scroll-view>
  </template>
</template>

<style lang="scss">
page {
  background-color: #f7f7f7;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.scroll-view {
  flex: 1;
}
</style>
